package com.lottery.service;

import com.lottery.model.CombinationResult;
import com.lottery.model.MatchSelection;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class PythonStyleImageService {
    private static final int WIDTH = 950; // 增加宽度以适应布局
    private static final int MARGIN = 20;
    private static final int TITLE_HEIGHT = 30;
    private static final int HEADER_HEIGHT = 35;
    private static final Color CELL_BORDER_COLOR = new Color(0xe0e0e0); // 单元格边框颜色

    // 字体定义
    private static Font TITLE_FONT;
    private static Font HEADER_FONT;
    private static Font CONTENT_FONT;
    private static Font SMALL_FONT;

    // 颜色定义
    private static final Color WIN_SELECTED_COLOR = new Color(0xc62828); // 胜选项选中颜色
    private static final Color DRAW_SELECTED_COLOR = new Color(0xc62828); // 平选项选中颜色
    private static final Color LOSE_SELECTED_COLOR = new Color(0xc62828); // 负选项选中颜色
    private static final Color UNSELECTED_COLOR = Color.WHITE;       // 未选中的白色背景
    private static final Color SELECTED_TEXT_COLOR = Color.WHITE;    // 选中项文字颜色
    private static final Color UNSELECTED_TEXT_COLOR = new Color(0x333333); // 未选中项文字颜色
    private static final Color BORDER_COLOR = new Color(0xe0e0e0);   // 边框颜色
    private static final Color TITLE_COLOR = new Color(0x333333);    // 标题颜色
    private static final Color STATS_COLOR = new Color(0x666666);    // 统计信息颜色
    private static final Color HEADER_BG_COLOR = new Color(0xf5f5f5); // 表头背景色
    private static final Color LEAGUE_TEXT_COLOR = Color.BLACK;      // 联赛队伍黑色字体


    // 静态初始化字体
    static {
        try {
            TITLE_FONT = new Font("SimHei", Font.BOLD, 18);
            HEADER_FONT = new Font("SimHei", Font.BOLD, 14);
            CONTENT_FONT = new Font("SimHei", Font.PLAIN, 14);
            SMALL_FONT = new Font("SimHei", Font.PLAIN, 12);
        } catch (Exception e) {
            // 字体 fallback
            TITLE_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 18);
            HEADER_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 14);
            CONTENT_FONT = new Font(Font.SANS_SERIF, Font.PLAIN, 14);
            SMALL_FONT = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
        }
    }

    public byte[] generateCombinationImage(CombinationResult result) throws IOException {
        if (result == null || result.getCombinations() == null || result.getCombinations().isEmpty()) {
            throw new IllegalArgumentException("组合数据不能为空");
        }

        // 计算图片高度 - 增加高度避免溢出
        int totalHeight = MARGIN * 2 + TITLE_HEIGHT + HEADER_HEIGHT + 30;
        for (List<MatchSelection> combo : result.getCombinations()) {
            // 为每场比赛增加更多高度，确保内容不溢出
            int comboHeight = 50 + combo.size() * 50; // 增加高度
            totalHeight += comboHeight + 30; // 增加组合间距
        }

        BufferedImage image = new BufferedImage(WIDTH, totalHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // 白色背景
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, totalHeight);

        // 标题
        g.setColor(TITLE_COLOR);
        g.setFont(TITLE_FONT);
        String title = "胜负彩任9组合 - " + new SimpleDateFormat("yyyyMMdd").format(new Date());
        drawCenteredString(g, title, MARGIN, MARGIN + TITLE_HEIGHT - 5, WIDTH - MARGIN * 2);

        // 统计信息
        g.setColor(STATS_COLOR);
        g.setFont(SMALL_FONT);
        String stats = String.format("总组合数: %d | 总注数: %d | 总金额: %.2f元",
                result.getTotalCombinations(),
                result.getTotalBets(),
                result.getTotalAmount());
        g.drawString(stats, MARGIN + 5, MARGIN + TITLE_HEIGHT + HEADER_HEIGHT - 5);


        // 绘制组合
        int yPos = MARGIN + TITLE_HEIGHT + HEADER_HEIGHT;
        for (int i = 0; i < result.getCombinations().size(); i++) {
            List<MatchSelection> combo = result.getCombinations().get(i);

            // 计算组合金额
            int betCount = combo.stream()
                    .mapToInt(match -> match.getSelections().size())
                    .reduce(1, (a, b) -> a * b);
            double amount = betCount * 2.0;

            // 组合区域
            int comboHeight = 50 + combo.size() * 50; // 增加高度
            // 绘制组合背景
            g.setColor(Color.WHITE);
            g.fillRect(MARGIN, yPos, WIDTH - MARGIN * 2, comboHeight);

            // 绘制组合边框
            g.setColor(BORDER_COLOR);
            g.drawRect(MARGIN, yPos, WIDTH - MARGIN * 2, comboHeight);

            // 组合标题
            g.setFont(CONTENT_FONT);
            g.setColor(TITLE_COLOR);
            g.drawString(String.format("组合 %d (金额: %.2f元)", (i + 1), amount),
                    MARGIN + 10, yPos + 30);

            // 绘制表头
            int headerY = yPos + 45; // 调整表头位置
            g.setColor(TITLE_COLOR);
            g.setFont(HEADER_FONT);

            // 绘制表头单元格背景
            g.setColor(HEADER_BG_COLOR);

            // 场次序号列背景 (新增)
            g.fillRect(MARGIN, headerY, WIDTH * 5 / 100, HEADER_HEIGHT);

            // 联赛列背景
            g.fillRect(MARGIN + WIDTH * 5 / 100, headerY, WIDTH * 20 / 100, HEADER_HEIGHT);

            // 胜平负三列合并背景
            g.fillRect(MARGIN + WIDTH * 25 / 100, headerY, WIDTH * 75 / 100 - MARGIN, HEADER_HEIGHT);

            // 绘制表头文字
            // 场次序号列标题 (新增)
            drawCenteredString(g, "场次", MARGIN, headerY + 25, WIDTH * 5 / 100);

            // 联赛列标题
            g.drawString("联赛", MARGIN + WIDTH * 5 / 100 + 10, headerY + 25);

            // 绘制胜平负表头文字
            int spfStart = MARGIN + WIDTH * 25 / 100;
            int winWidth = WIDTH * 25 / 100;
            int drawWidth = WIDTH * 15 / 100;
            int loseWidth = WIDTH * 35 / 100 - MARGIN;

            drawCenteredString(g, "胜（主队）", spfStart, headerY + 25, winWidth);
            drawCenteredString(g, "平", spfStart + winWidth, headerY + 25, drawWidth);
            drawCenteredString(g, "负（客队）", spfStart + winWidth + drawWidth, headerY + 25, loseWidth);

            // 绘制表头下方的分隔线
            g.setColor(CELL_BORDER_COLOR);
            g.drawLine(MARGIN, headerY + HEADER_HEIGHT, WIDTH - MARGIN, headerY + HEADER_HEIGHT);


            // 绘制比赛信息
            g.setFont(CONTENT_FONT);
            int matchYPos = headerY + HEADER_HEIGHT + 15; // 调整比赛内容位置

            for (int j = 0; j < combo.size(); j++) {
                MatchSelection match = combo.get(j);
                int rowHeight = 50; // 增加行高
                int cellTop = matchYPos - 30;
                int cellBottom = matchYPos + 20;

                // 绘制行背景
                g.setColor(j % 2 == 0 ? new Color(0xfafafa) : Color.WHITE);
                g.fillRect(MARGIN, cellTop, WIDTH - MARGIN * 2, rowHeight);

                // 1. 场次序号列 - 不绘制线框
                g.setColor(UNSELECTED_TEXT_COLOR);
                drawCenteredString(g, String.valueOf(match.getMatchId()), MARGIN, matchYPos, WIDTH * 5 / 100);

                // 2. 联赛列 - 不绘制线框，使用黑色字体
                g.setColor(LEAGUE_TEXT_COLOR); // 设置为黑色
                drawLeftAlignedString(g, match.getLeague() != null ? match.getLeague() : "",
                        MARGIN + WIDTH * 5 / 100 + 5, matchYPos, WIDTH * 20 / 100 - 10);

                // 计算胜平负列宽度和位置
                int winColWidth = WIDTH * 25 / 100;
                int drawColWidth = WIDTH * 15 / 100;
                int loseColWidth = (WIDTH * 35 / 100) - MARGIN;

                int winColStart = MARGIN + WIDTH * 25 / 100;
                int drawColStart = winColStart + winColWidth;
                int loseColStart = drawColStart + drawColWidth;

                // 3. 胜选项
                boolean winSelected = match.getSelections().contains("3");
// 修复队伍名称显示，直接使用从API获取的名称
                String winText = String.format("(%.2f) %s", match.getOdds3(), match.getHome());

// 绘制胜选项背景
                g.setColor(winSelected ? WIN_SELECTED_COLOR : UNSELECTED_COLOR);
                g.fillRect(winColStart, cellTop, winColWidth, rowHeight);

// 绘制胜选项边框
                g.setColor(CELL_BORDER_COLOR);
                g.drawRect(winColStart, cellTop, winColWidth, rowHeight);

// 绘制胜选项文字
                drawWrappedText(g, winText, winColStart, matchYPos, winColWidth,
                        winSelected ? SELECTED_TEXT_COLOR : UNSELECTED_TEXT_COLOR);

                // 4. 平选项
                boolean drawSelected = match.getSelections().contains("1");
                String drawText = String.format("(%.2f)", match.getOdds1());

                // 绘制平选项背景
                g.setColor(drawSelected ? DRAW_SELECTED_COLOR : UNSELECTED_COLOR);
                g.fillRect(drawColStart, cellTop, drawColWidth, rowHeight);

                // 绘制平选项边框
                g.setColor(CELL_BORDER_COLOR);
                g.drawRect(drawColStart, cellTop, drawColWidth, rowHeight);

                // 绘制平选项文字
                drawCenteredString(g, drawText, drawColStart, matchYPos, drawColWidth);

                // 5. 负选项
                boolean loseSelected = match.getSelections().contains("0");
                String loseText = String.format("(%.2f) %s", match.getOdds0(), match.getAway());

// 绘制负选项背景
                g.setColor(loseSelected ? LOSE_SELECTED_COLOR : UNSELECTED_COLOR);
                g.fillRect(loseColStart, cellTop, loseColWidth, rowHeight);

// 绘制负选项边框
                g.setColor(CELL_BORDER_COLOR);
                g.drawRect(loseColStart, cellTop, loseColWidth, rowHeight);

// 绘制负选项文字
                drawWrappedText(g, loseText, loseColStart, matchYPos, loseColWidth,
                        loseSelected ? SELECTED_TEXT_COLOR : UNSELECTED_TEXT_COLOR);

                // 移动到下一行
                matchYPos += rowHeight;
            }

            // 移动到下一个组合
            yPos += comboHeight + 30;
        }

        g.dispose();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        return baos.toByteArray();
    }

    // 辅助方法：居中绘制字符串
    private void drawCenteredString(Graphics g, String text, int x, int y, int width) {
        FontMetrics metrics = g.getFontMetrics();
        int textX = x + (width - metrics.stringWidth(text)) / 2;
        g.drawString(text, textX, y);
    }

    // 辅助方法：左对齐绘制字符串
    private void drawLeftAlignedString(Graphics g, String text, int x, int y, int maxWidth) {
        FontMetrics metrics = g.getFontMetrics();
        // 如果文本过长，截断并添加省略号
        if (metrics.stringWidth(text) > maxWidth) {
            String ellipsis = "...";
            int ellipsisWidth = metrics.stringWidth(ellipsis);
            int availableWidth = maxWidth - ellipsisWidth;

            for (int i = text.length(); i > 0; i--) {
                String truncated = text.substring(0, i);
                if (metrics.stringWidth(truncated) <= availableWidth) {
                    g.drawString(truncated + ellipsis, x, y);
                    return;
                }
            }
        }
        g.drawString(text, x, y);
    }

    // 辅助方法：自动换行绘制文本
    private void drawWrappedText(Graphics g, String text, int x, int y, int width, Color color) {
        g.setColor(color);
        FontMetrics metrics = g.getFontMetrics();
        String[] words = text.split(" ");
        StringBuilder currentLine = new StringBuilder();

        for (String word : words) {
            String testLine = currentLine.length() == 0 ? word : currentLine + " " + word;
            if (metrics.stringWidth(testLine) <= width) {
                currentLine = new StringBuilder(testLine);
            } else {
                drawCenteredString(g, currentLine.toString(), x, y, width);
                currentLine = new StringBuilder(word);
                y += metrics.getHeight();
            }
        }

        if (currentLine.length() > 0) {
            drawCenteredString(g, currentLine.toString(), x, y, width);
        }
    }
}